package xps.and.uudaijia.userclient.view.base;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jude.utils.JUtils;

import java.util.ArrayList;
import java.util.List;

import xps.and.uudaijia.userclient.App;
import xps.and.uudaijia.userclient.Constants;
import xps.and.uudaijia.userclient.R;
import xps.and.uudaijia.userclient.adapter.AbstractRecyclerAdapter;
import xps.and.uudaijia.userclient.util.LazyFragmentControl;


public abstract class BaseSwipeRefreshFragment extends android.support.v4.app.Fragment implements SwipeRefreshLayout.OnRefreshListener, AbstractRecyclerAdapter.LoadMoreListener, View.OnClickListener, LazyFragmentControl {
    protected SwipeRefreshLayout swipeRefreshLayout;

    protected RecyclerView recyclerView;

    protected int pageIndex = Constants.PAGE_INDEX;
    protected int loadMethod = 0;

    protected List adapterListData = new ArrayList();

    protected int pageSize = Constants.PAGE_SIZE;

    protected AbstractRecyclerAdapter<?> abstractRecyclerAdapter;

    protected LinearLayout mNetworkErrorLayout;

    protected ImageView mNetworkErrorIcon;
    protected TextView mNetworkErrorTip;
    protected FrameLayout containerLayout;

    protected Activity activity;

    protected boolean isVisibleToUser;

    protected String loadFrom = Constants.LOAD_NET;

    private int failedLoadTimes = 0;

    private boolean isPrepared;
    /**
     * 第一次onResume中的调用onUserVisible避免操作与onFirstUserVisible操作重复
     */
    private boolean isFirstResume = true;
    private boolean isFirstVisible = true;
    private boolean isFirstInvisible = true;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_swiperefresh, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        swipeRefreshLayout.setOnRefreshListener(this);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        recyclerView.setBackgroundColor(getResources().getColor(R.color.common_background));
        abstractRecyclerAdapter.setAutoLoadMoreEnable(false);
        abstractRecyclerAdapter.setLoadMoreListener(this);
        recyclerView.setAdapter(abstractRecyclerAdapter);
        mNetworkErrorTip.setOnClickListener(this);
        mNetworkErrorIcon.setOnClickListener(this);

        initPrepare();
    }

    public void setRefreshEnable(boolean enable){
        swipeRefreshLayout.setEnabled(enable);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstResume) {
            isFirstResume = false;
            return;
        }
        if (getUserVisibleHint()) {
            onUserVisible();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        if (getUserVisibleHint()) {
            onUserInvisible();
        }
    }

    protected void initView(View viewLayout) {
        containerLayout = r2v(viewLayout, R.id.containerLayout);
        recyclerView = r2v(viewLayout, R.id.recycler_view);
        swipeRefreshLayout = r2v(viewLayout, R.id.refresh_layout);
        mNetworkErrorLayout = (LinearLayout) viewLayout.findViewById(R.id.ll_network_error);
        mNetworkErrorTip = (TextView) viewLayout.findViewById(R.id.network_status);
        mNetworkErrorIcon = (ImageView) viewLayout.findViewById(R.id.state_icon);
        mNetworkErrorLayout.setVisibility(View.GONE);
    }

    @Override
    public void onRefresh() {
        try {
            if (swipeRefreshLayout.getVisibility() == View.GONE) {
                swipeRefreshLayout.setVisibility(View.VISIBLE);
            }

            if (mNetworkErrorLayout.getVisibility() == View.VISIBLE) {
                mNetworkErrorLayout.setVisibility(View.GONE);
            }

            if (!swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.post(new Runnable() {

                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(true);
                    }
                });
            }

            if (pageIndex > 1) {
                abstractRecyclerAdapter.initLoading(false);
            }
            loadMethod = 0;
            pageIndex = Constants.PAGE_INDEX;
            loadFrom = Constants.LOAD_NET;
            //getData(pageIndex);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLoadMore() {
        loadMethod = 1;
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        loadFrom = Constants.LOAD_NET;
        getData(++pageIndex);
    }

    public void onFail() {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        if (loadMethod == 1) {//正在加载更多
            abstractRecyclerAdapter.showLoadMoreFailed(true,null);
            abstractRecyclerAdapter.setLoadingMore(false);
            if (pageIndex > 1) {
                pageIndex--;
            }
            JUtils.Toast(App.getInstance().getResources().getString(R.string.network_connect_error));
        } else if (loadMethod == 0) {//正在刷新
            swipeRefreshLayout.setVisibility(View.GONE);
            mNetworkErrorLayout.setVisibility(View.VISIBLE);
            mNetworkErrorIcon.setImageResource(R.drawable.ic_empty_data);
            mNetworkErrorTip.setText(activity.getResources().getString(R.string.network_connect_error));
            pageIndex = Constants.PAGE_INDEX;
            loadFrom = Constants.LOAD_CACHE;
            if (failedLoadTimes == 0) {
                failedLoadTimes = 1;
                getData(pageIndex);
            }
        }
    }

    public void onFail(String hint) {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        if (loadMethod == 1) {//正在加载更多
            abstractRecyclerAdapter.showLoadMoreFailed(true,hint);
            abstractRecyclerAdapter.setLoadingMore(false);
            if (pageIndex > 1) {
                pageIndex--;
            }
        } else if (loadMethod == 0) {//正在刷新
            swipeRefreshLayout.setVisibility(View.GONE);
            mNetworkErrorLayout.setVisibility(View.VISIBLE);
            mNetworkErrorIcon.setImageResource(R.drawable.ic_empty_data);
            mNetworkErrorTip.setText(hint);
            pageIndex = Constants.PAGE_INDEX;
            loadFrom = Constants.LOAD_CACHE;
            if (failedLoadTimes == 0) {
                failedLoadTimes = 1;
                getData(pageIndex);

            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;

        if (isVisibleToUser) {
            if (isFirstVisible) {
                isFirstVisible = false;
                initPrepare();
            } else {
                onUserVisible();
            }
        } else {
            if (isFirstInvisible) {
                isFirstInvisible = false;
                onFirstUserInvisible();
            } else {
                //界面不显示 设置上次显示时间
                onUserInvisible();
            }
        }
    }

    public void onResponce() {
        if (null != adapterListData && adapterListData.size() > 0) {
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            mNetworkErrorLayout.setVisibility(View.GONE);
            if (loadMethod == 0) {
                swipeRefreshLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
                abstractRecyclerAdapter.setRes(adapterListData);
            } else if (loadMethod == 1) {
                if (swipeRefreshLayout.isRefreshing()) {
                    swipeRefreshLayout.setRefreshing(false);
                }
                /**
                 * 加载更多失败后,重新显示加载中
                 */
                abstractRecyclerAdapter.showLoadMoreFailed(false,null);
                abstractRecyclerAdapter.notifyMoreFinish();
                abstractRecyclerAdapter.appendData(adapterListData);
            }
            if (adapterListData.size() < pageSize) {
                if (pageIndex > 1) {
                    abstractRecyclerAdapter.setAutoLoadMoreEnable(true);
                    abstractRecyclerAdapter.loadFinish(true);
                } else {
                    abstractRecyclerAdapter.setAutoLoadMoreEnable(false);
                }
            } else {
                abstractRecyclerAdapter.setAutoLoadMoreEnable(true);
            }
        } else {
            if (loadMethod == 0) {
                swipeRefreshLayout.setRefreshing(false);
                swipeRefreshLayout.setVisibility(View.GONE);
                mNetworkErrorLayout.setVisibility(View.VISIBLE);

                mNetworkErrorIcon.setImageResource(R.drawable.ic_empty_data);
                mNetworkErrorTip.setText(activity.getResources().getString(R.string.no_data));
            } else if (loadMethod == 1) {
                if (pageIndex > 1) {
                    abstractRecyclerAdapter.setAutoLoadMoreEnable(true);
                    abstractRecyclerAdapter.loadFinish(true);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v == mNetworkErrorIcon || v == mNetworkErrorTip) {
            onRefresh();
        }
    }

    protected abstract void getData(int pageIndex);

    @SuppressWarnings("unchecked")
    protected <T extends View> T r2v(View view, int resId) {
        return (T) view.findViewById(resId);
    }

    @SuppressWarnings("unchecked")
    protected <T extends View> T r2v(int resId) {
        return (T) activity.findViewById(resId);
    }

    @Override
    public void initPrepare() {
        if (isPrepared) {
            onFirstUserVisible();
            lazyData();
        } else {
            isPrepared = true;
        }
    }

    @Override
    public void onFirstUserVisible() {

    }

    @Override
    public void onUserVisible() {

    }

    @Override
    public void onFirstUserInvisible() {

    }

    @Override
    public void onUserInvisible() {

    }

    @Override
    public void lazyData() {

    }
}
